package com.example.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.api.model.PruneType;
import com.github.dockerjava.api.model.PullResponseItem;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.Closeable;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class ImageController {
    @Resource
    DockerClient dockerClient;

    @GetMapping("/image")
    public ModelAndView page() {
        return new ModelAndView("image");
    }

    @GetMapping("/image/prune")
    public void prune() {
        dockerClient.pruneCmd(PruneType.IMAGES).exec();
    }

    @GetMapping("/image/pull")
    public void pull(String name) {
        ResultCallback<PullResponseItem> resultCallback = new ResultCallback<>() {
            @Override
            public void onStart(Closeable closeable) {
            }

            @Override
            public void onNext(PullResponseItem object) {
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onComplete() {
            }

            @Override
            public void close() {
            }
        };
        dockerClient.pullImageCmd(name).exec(resultCallback);
    }

    @GetMapping("/image/list")
    public List<Image> list() {
        List<Image> imageList = dockerClient.listImagesCmd().withDanglingFilter(false).exec();
        return imageList.stream().sorted(Comparator.comparing(i -> i.getRepoTags()[0])).collect(Collectors.toList());
    }

    @DeleteMapping("/image/{id}")
    public void delete(@PathVariable String id) {
        dockerClient.removeImageCmd(id).withForce(Boolean.TRUE).exec();
    }
}
